package service

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"time"
	"video_src/basic/appConfig"
	__ "video_src/basic/proto"
	"video_src/handler/models"
)

// SayHello implements helloworld.GreeterServer
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {

	result, _ := appConfig.Rdb.Get(appConfig.Ctx, "smsCount"+in.Mobile).Result()
	if result >= "3" {
		return nil, fmt.Errorf("同一手机号5分钟内最多发送3条验证码")
	}

	code := rand.Intn(900000) + 100000

	//sms, _ := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}

	appConfig.Rdb.Set(appConfig.Ctx, "sendSms"+in.Mobile, code, time.Minute*5)

	incr := appConfig.Rdb.Incr(appConfig.Ctx, "smsCount"+in.Mobile)
	if incr.Val() == 1 {
		appConfig.Rdb.Set(appConfig.Ctx, "smsCount"+in.Mobile, 1, time.Minute*5)
	}

	return &__.SendSmsResp{
		Msg: "短信验证码发送成功",
	}, nil
}

func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	var err error
	var u models.User

	if err = u.GetUserByMobile(appConfig.DB, in.Mobile); err != nil {
		return nil, errors.New("用户信息获取失败！")
	}
	result, _ := appConfig.Rdb.Get(appConfig.Ctx, "sendSms"+in.Mobile).Result()
	if in.SmsCode != result {
		return nil, errors.New("短信验证码错误")
	}
	if u.ID == 0 {
		u.Mobile = in.Mobile
		u.Password = in.Password

		if err = u.Register(appConfig.DB); err != nil {
			return nil, errors.New("注册失败！")
		}
	} else {
		return nil, errors.New("该手机号已注册！")
	}
	return &__.RegisterResp{
		Id: int64(u.ID),
	}, nil
}

func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var err error
	var u models.User

	if err = u.GetUserByMobile(appConfig.DB, in.Mobile); err != nil {
		return nil, errors.New("用户信息获取失败！")
	}
	result, _ := appConfig.Rdb.Get(appConfig.Ctx, "sendSms"+in.Mobile).Result()
	if in.SmsCode != result {
		return nil, errors.New("短信验证码错误")
	}
	if u.ID == 0 {
		return nil, errors.New("该手机号未注册账号")
	}

	return &__.LoginResp{
		Id: int64(u.ID),
	}, nil
}
